package com.wuzhen.wzzt.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wuzhen.wzzt.core.ret.RetCode;
import com.wuzhen.wzzt.core.ret.RetResponse;
import com.wuzhen.wzzt.core.ret.RetResult;
import com.wuzhen.wzzt.core.utils.AddressUtils;
import com.wuzhen.wzzt.model.ActiveInfo;
import com.wuzhen.wzzt.model.EnrollUser;
import com.wuzhen.wzzt.model.LocationDto;
import com.wuzhen.wzzt.service.ActiveService;
import com.wuzhen.wzzt.service.RedisService;
import com.wuzhen.wzzt.vo.ActiveIdVo;
import com.wuzhen.wzzt.vo.ActiveTypeVo;
import com.wuzhen.wzzt.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhengzheng
 * @Description: ActiveController
 * @date 2022年4月1日 11:28
 */
@RestController
@RequestMapping("/active")
@Api(tags = {"活动相关接口"}, description = "ActiveController", position = 1)
public class ActiveController {
    private static Logger logger = LoggerFactory.getLogger(ActiveController.class);

    @Resource
    private ActiveService activeService;

    @Resource
    private RedisService redisService;

    @Value("${root.pic.url}")
    private String rootPicUrl;

    /**
     * 活动详情查询
     *
     * @param activeIdVo
     * @return
     * @throws Exception
     */
    @PostMapping("/selectById")
    @ApiOperation(value = "活动详情", notes = "根据活动ID查询活动详情")
    public RetResult<ActiveInfo> selectById(@RequestHeader(value = "thirdSessionKey", required = false) String thirdSessionKey, @RequestBody ActiveIdVo activeIdVo) throws Exception {
        logger.info("活动详情接口，入参:,thirdSessionKey:{},activeIdVo:{}", thirdSessionKey, activeIdVo.toString());
        boolean noSessionFlag = false;
        String openIdStr = "";
        try {
            if (thirdSessionKey == null || "".equals(thirdSessionKey)) {
                logger.info("进入活动详情查询，入参:{}", activeIdVo.getId());
                noSessionFlag = true;
            } else {
                openIdStr = redisService.get(thirdSessionKey);
                openIdStr = openIdStr.split("#")[1];
                logger.info("根据token：{}，查询到oepnid结果:{}", thirdSessionKey, openIdStr);
                if (openIdStr == null || "".equals(openIdStr)) {
                    noSessionFlag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("活动详情查询异常.{}", e);
            noSessionFlag = true;
        } finally {

            ActiveInfo activeInfo = activeService.selectActById(activeIdVo.getId());
            if (activeInfo != null) {
                LocationDto lngAndLat = AddressUtils.getLngAndLat(activeInfo.getAddress());

                if(Objects.nonNull(lngAndLat)){
                    activeInfo.setLat(lngAndLat.getLat());
                    activeInfo.setLng(lngAndLat.getLng());
                }
                this.setLpValue(activeInfo);
                this.setPicValue(activeInfo);
                this.setActiveStatus(activeInfo);
            } else {
                return RetResponse.makeOKRsp();
            }

            if (noSessionFlag || openIdStr == null || "".equals(openIdStr)) {
                logger.info("活动详情返回结果：{}", activeInfo.toString());
                activeInfo.setIsUserEnrollStatus("0");//用户未报名
                return RetResponse.makeOKRsp(activeInfo);
            } else {
                EnrollUser enrollUser = activeService.selectActiveInfoById(activeIdVo.getId(), openIdStr);
                if (enrollUser!=null){
                    activeInfo.setIsUserEnrollStatus("1");//用户已报名
                    activeInfo.setEnrollUser(enrollUser);
                }else {
                    activeInfo.setIsUserEnrollStatus("0");//用户未报名
                }
                return RetResponse.makeOKRsp(activeInfo);
            }
        }

    }


    /**
     * 查询列表
     *
     * @param activeTypeVo
     * @Description: 分页查询
     * @Reutrn RetResult<PageInfo < ActiveInfo>>
     */
    @PostMapping("/list")
    @ApiOperation(value = "活动列表", notes = "根据活动类型【1-智展，2-智会】查询活动详情")
    public RetResult<PageInfo<ActiveInfo>> list(@RequestBody ActiveTypeVo activeTypeVo) throws Exception {
        logger.info("活动列表，入参:activeTypeVo：{}", activeTypeVo.toString());
        PageHelper.startPage(activeTypeVo.getPage(), activeTypeVo.getSize());
        List<ActiveInfo> list = activeService.selectList(activeTypeVo.getActiveType());
        list.forEach(activeInfo -> {
            this.setPicValue(activeInfo);
            this.setActiveStatus(activeInfo);

        });
        logger.info("活动列表查询返回记录条数：{}条", list.size());
        PageInfo<ActiveInfo> pageInfo = new PageInfo<ActiveInfo>(list);
        return RetResponse.makeOKRsp(pageInfo);
    }


    /**
     * 我的活动列表
     *
     * @param thirdSessionKey
     * @return
     * @throws Exception
     */
    @PostMapping("/myActiveList")
    @ApiOperation(value = "我的活动列表", notes = "根据会话token【thirdSessionKey】查询活动详情")
    public RetResult<PageInfo<ActiveInfo>> myActiveList(@RequestHeader(value = "thirdSessionKey", required = true) String thirdSessionKey, @RequestBody PageVo pageVo) throws Exception {
        PageHelper.startPage(pageVo.getPage(), pageVo.getSize());
        logger.info("我的活动列表，入参:page：{},size:{},token:{}", pageVo.getPage(), pageVo.getSize(), thirdSessionKey);
        String openIdStr = redisService.get(thirdSessionKey);
        logger.info("{}查询到的openid：{}", thirdSessionKey, openIdStr);
        if (openIdStr == null) {
            return RetResponse.makeRsp(RetCode.WX_SESSION_TIMEOUT.code, "会话失效");
        } else {
            openIdStr = openIdStr.split("#")[1];
        }

        List<ActiveInfo> list = activeService.selectListByOpenid(openIdStr);
        list.forEach(activeInfo -> {
            this.setPicValue(activeInfo);
            this.setActiveStatus(activeInfo);
            this.setActiveStatus(activeInfo);
        });
        logger.info("我的活动列表条数：{}", list.size());
        PageInfo<ActiveInfo> pageInfo = new PageInfo<ActiveInfo>(list);
        return RetResponse.makeOKRsp(pageInfo);
    }


    private void setPicValue(ActiveInfo activeInfo) {
        if (activeInfo != null) {
            if (activeInfo.getFpFilesName() != null && !"".equals(activeInfo.getFpFilesName())) {
                activeInfo.setFpFilesName(rootPicUrl + "/fp/" + activeInfo.getFpFilesName());
            }
            if (activeInfo.getLsFilesName() != null && !"".equals(activeInfo.getLsFilesName())) {
                activeInfo.setLsFilesName(rootPicUrl + "/ls/" + activeInfo.getLsFilesName());
            }
        }
    }

    private void setLpValue(ActiveInfo activeInfo) {
        if (activeInfo != null) {
            if (activeInfo.getLpFilesName() != null && !"".equals(activeInfo.getLpFilesName())) {
                String[] lpNames = activeInfo.getLpFilesName().split(",");
                if (lpNames.length > 0) {
                    List<String> listName = new ArrayList<>();
                    for (String name : lpNames) {
                        listName.add(rootPicUrl + "/lp/" + name);
                    }
                    activeInfo.setListLpNames(listName);
                }
            }
        }

    }

    private static String judgeDate(String startdate, String enddate) {
        String retStauts = "3";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotEmpty(startdate) && StringUtils.isNotEmpty(enddate)) {
            try {
                Date dateStart = simpleDateFormat.parse(startdate);
                Date dateEnd = simpleDateFormat.parse(enddate);
                dateEnd = dateAddOne(dateEnd);
                Date dateNow = new Date();

                if (dateStart.after(dateNow)) {
                    //未开始
                    retStauts = "0";
                } else if ((dateStart.before(dateNow) && dateEnd.after(dateNow)) || (dateStart.equals(dateNow)) || (dateEnd.equals(dateNow))) {
                    //进行中
                    retStauts = "1";
                } else if (dateNow.after(dateEnd)) {
                    //已结束
                    retStauts = "2";
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return retStauts;
    }


    /*日期加+1天*/
    public static Date dateAddOne(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        //把日期往后增加一天,整数  往后推,负数往前移动
        calendar.add(calendar.DATE, 1);
        //这个时间就是日期往后推一天的结果
        date = calendar.getTime();
        return date;

    }

    private void setActiveStatus(ActiveInfo activeInfo) {
        activeInfo.setActiveStatus(judgeDate(activeInfo.getActiveStartDate(), activeInfo.getActiveEndDate()));
        activeInfo.setEnrollStatus(judgeDate(activeInfo.getEnrollStartDate(), activeInfo.getEnrollEndDate()));
    }

}